package com.htfyun.eink.pw.core.manager;

import android.util.Log;

import androidx.annotation.NonNull;

import com.htfyun.eink.pw.core.EinkManagerDummy;
import com.htfyun.eink.pw.core.IEinkManager;

import java.lang.reflect.Constructor;
import java.util.concurrent.atomic.AtomicReference;

public class EinkManagerFactoryHelper {
    private static final String TAG = EinkManagerFactoryHelper.class.getSimpleName();

    private static final AtomicReference<IEinkManager> sCachedRef = new AtomicReference<>();

    private final static String CLS_IMPL = "com.htfyun.eink.pw.core.EinkManagerImpl";

    @NonNull
    public static IEinkManager getEinkManager() {
        IEinkManager manager = sCachedRef.get();
        if (manager != null) {
            return manager;
        }
        manager = createEinkManager();
        sCachedRef.set(manager);
        return manager;
    }

    @NonNull
    private static IEinkManager createEinkManager() {
        try {
            Class<?> optClass = Class.forName(CLS_IMPL);
            Constructor<?> constructor = optClass.getConstructor();
            return (IEinkManager) constructor.newInstance();
        } catch (Exception e) {
            Log.e(TAG, "createEinkManager: failed with Exception!!", e);
            e.printStackTrace();
        }
        return new EinkManagerDummy();
    }
}
